<template>
	<view class="home-layout">
		  <u-sticky bgColor="#fff">
		     <u-tabs @click="handleClickTab" :inactiveStyle="tabsClass" lineColor="#fff" :activeStyle="activeTabsClass" :list="tabList"> </u-tabs>
		   </u-sticky>
		   <view class="content">
			   <new-item @tap="handleToDetail(item)" :newInfo="item" v-for="item in newList" :key="item.id" />
			   <u-loadmore :status="status" />
		   </view>
	</view>
</template>

<script setup>
	import { apiGetCategory, apiNewsList }  from '@/api/index.js'
	import { useNewLookHistory } from '@/store/history.js'
	//实例化store
	const newStore =  useNewLookHistory()
	// 创建响应式数据  
	const tabList = ref([]);
	const status = ref('loadmore')
	const newList = ref([])
	const lastSelectTab = ref(null)
	const pageParams = reactive({
		page: 1,
		cid: null,
		num: 8
	})
	const tabsClass = reactive({
		'line-height': '50px',
		width: '100rpx',
		'font-size': '40rpx !important'
	})
	const activeTabsClass = reactive({
		...tabsClass,
		color: '#31c27c'
	})
	const getHomeTabs = async () => {
		const  tabs = await apiGetCategory()
		tabList.value = tabs.map(item =>{
			return  { name: item.classname, id: item.id }
		})
		pageParams.cid = tabs[0].id
		getNewList()
	}
	const getNewList = async () => {
		const news = await apiNewsList({
			...pageParams
		})
		newList.value.push(...news)
		if(news.length < pageParams.num) {
			status.value = 'nomore'
		}
	}
	// 切换tab
	const handleClickTab = ({ id }) => {
		pageParams.cid = id
		pageParams.page = 1
		status.value = 'loadmore'
		if(id === lastSelectTab.value) return ;
		newList.value.splice(0)
		getNewList()
		lastSelectTab.value = id
	}
	// 监听触底
	onReachBottom(() => {
		if(status.value === 'nomore') return 
		status.value = 'loading'
		pageParams.page ++
		getNewList()
	})
	// 跳转
	const handleToDetail = (newObject)  => {
		let { id,classid: cid } = newObject
		uni.navigateTo({
			url:'/pages/detail/detail?id=' + id + '&cid=' + cid,
			success: () => {
				newStore.setNewsLog(newObject)
			},
			fail: () => {
				uni.showModal({
					title: '数据获取失败，无法跳转',
					showCancel: false
				})
			}
		})
	}
	getHomeTabs()
</script>

<style scoped lang="scss">
.content {
	padding: 30rpx;
	:deep() {
		.u-tabs__wrapper__nav__item__text {
			font-size: 30rpx !important; 
		}
	}
}
</style>
